import React, { useEffect } from 'react'
import { useCreateContentStore } from '../store'
import { useGlobalStore } from '@/store/global'
import { removeRoomData, unLockMeetingRoom } from '../blocks/basicInfo/store.room'
import { API_KIS_ROOM_PREFIX, API_MEETING_PREFIX } from '@/utils/constant'
const MSG_UNLOAD = '您有锁定的会议室，离开会导致会议室被释放'
/** 浏览器离开页面时解锁会议室 */
export default function useUnLoad() {
	useEffect(() => {
		const handelBeforeUnLoad = (e: BeforeUnloadEvent) => {
			const meetingFormKey = useCreateContentStore.getState().meetingFormKey
			if (meetingFormKey) {
				e = e || window.event
				e.returnValue = MSG_UNLOAD
				return MSG_UNLOAD
			}
		}

		const handelUnLoad = () => {
			if (!(useGlobalStore.getState().serverInfo?.enable_room && useGlobalStore.getState().user?.enable_kis))
				return
			const meetingFormKey = useCreateContentStore.getState().meetingFormKey
			const meetingMoid = useCreateContentStore.getState().meetingMoid
			if (meetingFormKey) {
				if (typeof navigator !== 'undefined' && navigator.sendBeacon) {
					var a = new FormData()
					a.append('token', window.KDV_BP_KEY)
					a.append('params', JSON.stringify({ meeting_form_key: meetingFormKey }))
					navigator.sendBeacon(API_KIS_ROOM_PREFIX + '/meeting_room_unlock', a)

					if (meetingMoid) {
						var b = new FormData()
						b.append('_method', 'DELETE')
						navigator.sendBeacon(API_MEETING_PREFIX + '/meetings/' + meetingMoid + '/meeting_rooms', b)
					}
				} else {
					unLockMeetingRoom(() => {
						removeRoomData()
					}, true)
				}
			}
		}
		window.addEventListener('beforeunload', handelBeforeUnLoad)
		window.addEventListener('unload', handelUnLoad)
		return () => {
			window.removeEventListener('beforeunload', handelBeforeUnLoad)
			window.removeEventListener('unload', handelUnLoad)
		}
	}, [])
}
